<template>
  <div>
    <el-form label-width="160px">
      <el-form-item label="数据源123" prop="connection">
        <el-popover
          ref="datasourceListPopover"
          v-model="srcTablePopover"
          placement="bottom-start"
          trigger="click"
        >
          <flink-table-tree
            ref="datasourceListTree"
            style="height: 400px; overflow-y: auto"
            @tableSelectHandler="tableSelectHandler"
          />
          <template #reference>
            <el-input v-model="srcTableName" :readonly="true" placeholder="点击选择数据源"/>
          </template>
        </el-popover>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import FlinkTableTree from './flink-table-tree.vue'
import http from '../../../../../utils/studioRequest'

export default {
  name: 'FlinkSqlDesign',
  components: {
    FlinkTableTree
  },
  data() {
    return {
      srcSelectVisible: false,
      srcId: '',
      srcName: '',
      tableList: [],
      tableName: '',
      tableCode: '',
      columnList: [],
      columnCheckedList: [],
      tableLoading: false,
      columnLoading: false,
      targetColumn: [],
      ruleList: [],
      ruleColumnList: [],
      useAlias: 0,
      allColumnSelected: false,
      filterText: '',
      show: false,
      isLoad: false, // 读取数据源时不刷新targetColumn
      srcTablePopover: false,
      srcTableName: '',
      activeTab: 'first'
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tableTree.filter(val)
    }
  },
  mounted() {
  },
  methods: {
    // 复杂sql
    init(form, name) {
      this.srcId = form.src
      this.srcTableName = name
      if (form.targetColumn && form.ruleList) {
        this.targetColumn = form.targetColumn
        this.isLoad = true
        for (const item of this.targetColumn) {
          item.id = item.columnId
        }
        this.ruleList = form.ruleList
        this.alias = form.alias
      }
    },
    // 简单选择表
    initTable(name, srcId) {
      this.srcId = srcId
      this.srcTableName = name
    },
    srcNodeClick(data, node) {
      if (node.isLeaf) {
        this.srcSelectVisible = false
        this.srcId = data.id
        this.srcName = data.name
        this.getTableList()
      }
    },
    getTableList() {
      this.tableList = []
      this.columnList = []
      this.allColumnSelected = false
      if (this.isLoad) {
        this.isLoad = false
      } else {
        this.targetColumn = []
        this.ruleList = []
      }
      this.tableLoading = true
      http({
        url: http.adornUrl(`/src/table/list`),
        method: 'get',
        params: http.adornParams({
          srcId: this.srcId,
          page: 1,
          limit: 1000
        })
      }).then(({ data }) => {
        this.tableLoading = false
        if (data && data.code === 0) {
          this.tableList = data.page.list
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    tableNodeClick(data, node) {
      this.tableName = data.tableName
      this.tableCode = data.tableCode
      this.getColumnList(data.id)
    },
    getColumnList(tableId) {
      this.columnCheckedList = []
      for (const item of this.targetColumn) {
        this.columnCheckedList.push(item.id)
      }
      this.columnLoading = true
      this.columnList = []
      this.allColumnSelected = false
      http({
        url: http.adornUrl(`/src/table/columnList/${tableId}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        this.columnLoading = false
        if (data && data.code === 0) {
          this.columnList = data.list
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    columnCheckChange(nodeData, checked) {
      if (checked) {
        this.appendColumn(nodeData)
      } else {
        this.removeColumn(nodeData.id)
      }
    },
    appendColumn(data) {
      const index = this.targetColumn.findIndex(
        d => d.id === data.id
      )
      const item = {
        id: data.id,
        showType: 1,
        tableColumn: this.tableCode + '.' + data.fieldCode,
        tableName: this.tableCode,
        columnName: data.fieldCode,
        columnTitle: this.tableName + '.' + data.fieldName,
        columnId: data.id
      }
      if (index < 0) {
        this.targetColumn.push(item)
      } else {
        this.targetColumn[index] = item
      }
    },
    removeColumn(id) {
      const index = this.targetColumn.findIndex(
        d => d.id === id
      )
      this.targetColumn.splice(index, 1)
    },
    addRuleRow() {
      this.ruleList.push({
        tableColumn: '',
        operate: '',
        targetTableColumn: '',
        value: ''
      })
    },
    deleteRuleRow(val) {
      this.ruleList.splice(val.$index, 1)
    },
    operateChange(operate, row) {
      if (operate !== 'LEFT JOIN' && operate !== 'RIGHT JOIN' && operate !== 'INNER JOIN' && operate !== 'ONE_TO_N') {
        row.targetTableColumn = '定值'
      } else {
        row.targetTableColumn = ''
      }
    },
    tableSelectHandler(data, node) {
      const form = {
        src: node.parent.data.id,
        srcName: node.parent.data.name,
        schema: data.schema,
        tableName: data.name,
        srcTableName: data.schemaTableName
      }
      // 数据源ID
      const datasourceId = data.parentId
      // 数据表名称
      const tableName = data.name
      const schemaName = data.schema
      const that = this
      const id = data.id
      this.srcTableName = data.schemaTableName
      this.srcTablePopover = false
      // 根据表名称，获取表字段信息
      const vFlinkDataBasePostData = {
        id: datasourceId,
        tableName: tableName
      }
      http({
        url: http.adornFlinkUrl(`/database/getColumn`),
        method: 'get',
        params: http.adornParams(vFlinkDataBasePostData, false)
      }).then(({ data }) => {
        if (data && data.code === 200) {
          const list = data.data
          if (list.length > 0) {
            this.$emit('showSQL', list, form)
          } else {
            this.$emit('showSQL', null, form)
          }
        } else {
          this.$message.error(data.message)
        }
      })
      this.srcPopover = false
    },
    showSQL() {
      this.show = false
      this.srcTableName = this.srcName
      http({
        url: http.adornUrl(`/src/dataset/sql`),
        method: 'post',
        data: http.adornData({
          'useAlias': this.useAlias,
          'extractList': this.ruleList,
          'destList': this.targetColumn
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          const form = {
            src: this.srcId,
            srcName: this.srcName,
            alias: this.useAlias,
            ruleList: this.ruleList,
            targetColumn: this.targetColumn
          }
          this.$emit('showSQL', data.selectSql, form)
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    selectAllColumn(checked) {
      const keys = []
      if (checked) {
        for (let i = 0; i < this.columnList.length; i++) {
          keys.push(this.columnList[i].id)
        }
      }
      this.$refs.columnTree.setCheckedKeys(keys, false)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.tableName.toLowerCase().indexOf(value) !== -1 || data.tableCode.toUpperCase().indexOf(value) !== -1
    }
  }
}
</script>

<style scoped>

</style>
